package concurrecy.util;

import java.util.PriorityQueue;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;

class PriorityTask implements Comparable<PriorityTask> {
    private int priority;
    private static int count = 0;
    private final int id = count ++;
    private CountDownLatch latch;

    public PriorityTask(int priority, CountDownLatch latch) {
        this.priority = priority;
        this.latch = latch;
    }

    public void run() {
        System.out.printf("[%-2d] [%-5d] run\n", id, priority);
        latch.countDown();
    }

    @Override
    public int compareTo(PriorityTask o) {
        return Integer.compare(this.priority, o.priority);
    }
}

/**
 * 优先级队列
 */
public class PriorityBlockingQueueDemo {
    final static int size = 20;
    public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newCachedThreadPool();
        Random random = new Random();
        CountDownLatch latch = new CountDownLatch(size);
        final PriorityBlockingQueue<PriorityTask> queue = new PriorityBlockingQueue<>();
        for (int i = 0; i < 20; i++) {
            queue.put(new PriorityTask(random.nextInt(10), latch));
        }
        service.execute(() -> {
            try {
                while (!Thread.interrupted()) {
                    queue.take().run();
                }
            } catch(InterruptedException e) {
                System.out.println("consumer interrupted");
            }
            System.out.println("consumer exit");
        });
        latch.await();
        System.out.println("all task is ran");
        service.shutdownNow();
    }
}
